<!DOCTYPE html>
<html>

<head>
  
  <meta charset="utf-8">
  <title></title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body {
      width: 100%;
      height: 100vh;
      background-color: #101010;
    }

    p {
      width: 400px;
      height: 280px;
      position: absolute;
      background-image: url('./run.gif');
      background-size: contain;
      background-position: -140px -50px;
      background-repeat: no-repeat;
    }
  </style>
</head>

<body>
  <p style="left: 0;top: 0px;;"></p>

  <script>
    // event.target  触发事件的dom 元素
    let body = document.querySelector("body")
    function myanimate(obj, x, y, callback) {
      //callback=function(){} 调用 callback()
      clearInterval(obj.timer);
      // 每次移动多少
      let move = function () {
        let left = Number.parseInt(obj.style.left)
        let top = Number.parseInt(obj.style.top)
        let stepX = getStep(left, x)
        let stepY = getStep(top, y)
        // // 设置缓动动画
        if (left != x) {
          obj.style.left = left + stepX + 'px';
        }
        if (top != y) {
          obj.style.top = top + stepY + 'px';
        }
        if (left == x && top == y) {
          clearInterval(obj.timer);
          //回调函数
          callback && callback();
        }
      }
      move()
      // obj.timer = setInterval(move, 500);
    }


    // 获取移动步长
    let getStep = function (start, end) {
      let between = Math.ceil(Math.abs(start - end) / 10)
      let i = 1
      if (end < start) {
        i = -1
      }
      if (between >= 10) {
        between = 10
      } else if (between >= 5) {
        between = 5
      }
      return between * i
    }
    let p = document.querySelector("p")
    // 每次鼠标点击 移动方块
    body.addEventListener("click", function () {
      // body 的坐标
      let x = event.x;
      let y = event.y;
      myanimate(p, x, y)
    })
    body.addEventListener("keydown",function () {
      let key = event.key
      if (key=='r') {
        p.style.backgroundImage = "url('./4.png')"
        setTimeout(() => {
          p.style.backgroundImage = "url('./run.gif')"
        },2000)
      }
      if (key=='e') {
        p.style.backgroundImage = "url('./3.gif')"
        setTimeout(() => {
          p.style.backgroundImage = "url('./run.gif')"
        },4000)
      }
      if (key=='w') {
        p.style.backgroundImage = "url('./2.gif')"
        setTimeout(() => {
          p.style.backgroundImage = "url('./run.gif')"
        },4000)
      }
    })
  </script>

</body>

</html>